<template>
  <div class="scan-box">
    <div>
      <el-affix :offset="94">
        <div class="card affix-container pt15 pb14">
          <el-page-header @back="router.go(-1)">
            <template #content>
              <!-- <span class="fsize16">{{ route.query.id ? "编辑优惠券" : "新增优惠券" }}</span> -->
              <span v-if="!route.query.id">扫码领券</span>
              <span v-else>{{ formData.name }}</span>
            </template>
            <template #extra>
              <div class="foot">
                <el-button @click="router.go(-1)">取消</el-button>
                <el-button @click="onSubmitMssalesPromotion" type="primary">保存</el-button>
              </div>
            </template>
          </el-page-header>
        </div>
      </el-affix>
    </div>

    <el-card style="width: 100%; margin-top: 10px">
      <!--<template #header>
        <div class="card-header" style="display: flex; aaaalign-items: center; justify-content: space-between">
          <div style="display: flex; align-items: center">
            <el-icon><ArrowLeft /></el-icon>
            <span v-if="!route.query.id">扫码领券</span>
            <span v-else>xxx</span>
          </div>
          <div>
            <el-button type="primary" @click="onSubmitMssalesPromotion">确认</el-button>
            <el-button>取消</el-button>
          </div>
        </div>
      </template>-->

      <div class="menu-demo">
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
          <el-menu-item index="menu1">基础信息</el-menu-item>
          <el-menu-item index="menu2">参与规则</el-menu-item>
          <el-menu-item index="menu3">活动规则</el-menu-item>
          <el-menu-item index="menu4">其他设置</el-menu-item>
          <el-menu-item index="menu5">分享设置</el-menu-item>
          <el-menu-item index="menu6">高级设置</el-menu-item>
        </el-menu>
      </div>

      <!-- 显示活动内容 -->
      <div style="padding: 20px" id="menu1">
        <h3 class="active">基础信息</h3>
        <!-- form表单 -->
        <el-form label-width="90px" :rules="scanRules" :model="formData" ref="mssalesPromotionRef">
          <el-form-item label="活动名称:" prop="name">
            <el-input style="width: 40%" v-model="formData.name" />
          </el-form-item>
          <el-form-item label="活动编码:">
            <el-input style="width: 40%" placeholder="请输入活动编码" v-model="formData.code" />
          </el-form-item>
          <el-form-item label="活动时间:" prop="validityRange" style="width: 43%">
            <el-date-picker
              format="YYYY-MM-DD HH:mm"
              v-model="formData.validityRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :size="size"
              default-time
            />
          </el-form-item>
          <el-form-item label="不可用日期:">
            <el-checkbox label="法定节假日" value="value" v-model="formData.noDate" />
          </el-form-item>
          <el-form-item label="活动说明:">
            <el-input type="textarea" placeholder="请输入活动说明" style="width: 40%" v-model="formData.desc" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 参与规则 -->
      <div style="padding: 20px" id="menu2">
        <h3 class="active">参与规则</h3>
        <!-- form表单 -->
        <el-form label-width="90px">
          <el-form-item label="适用门店:">
            <div>小桂林（东葛店）</div>
          </el-form-item>
          <el-form-item label="适用会员:">
            <el-radio-group v-model="isApplyMember">
              <el-radio :value="0" size="large">全部</el-radio>
              <el-radio :value="1" size="large">指定会员</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="会员选择:" v-if="isApplyMember">
            <el-checkbox-group v-model="memberCheck" @change="onChangeMember">
              <el-checkbox
                :label="item.title"
                :value="item.id"
                v-for="item in memberList"
                :key="item.id"
                :checked="item.checked"
              />
            </el-checkbox-group>
          </el-form-item>

          <!-- <el-form-item label="参与用户:">
            <div class="part-user">
              <div class="left" style="width: 300px">活动限制条件</div>
              <div class="right" style="flex: 1; height: 100%">
                <el-select v-model="restrict" size="small" style="width: 100px; padding: 20px">
                  <el-option label="不限制" :value="0" />
                  <el-option label="会员标签" :value="1" />
                </el-select>

                <el-select v-model="value" placeholder="请选择会员标签" style="width: 300px" v-if="restrict">
                   <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </div>
          </el-form-item> -->
        </el-form>
      </div>

      <!-- 活动规则 -->
      <div style="padding: 20px" id="menu3">
        <h3 class="active">活动规则</h3>
        <!-- form表单 -->
        <el-form label-width="90px">
          <el-form-item label="领取优惠券:">
            <div style="color: red" @click="dialogVisible = true" v-if="checkRuleList.length < 1">添加优惠券</div>
            <!-- 选中优惠券显示的表格 -->
            <div style="width: 80%" v-else>
              <span style="color: red" @click="dialogVisible = true">已选取{{ checkRuleList.length }}种优惠券</span>
              <el-table :data="checkRuleList" style="width: 100%">
                <el-table-column prop="date" label="序号" width="180">
                  <template #default="{ $index }">
                    <span>{{ $index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="id" label="券模版ID" width="180" />
                <el-table-column prop="name" label="券名称" />
                <el-table-column label="每人每次发券张数">
                  <template #default="{ row }">
                    <el-input-number v-model="row.count" :min="1" @change="handleChange(row, $event)" />
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="{ row }">
                    <el-button type="text" v-if="row">查看</el-button>
                    <el-button type="text" @click="onDelRule(row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>

          <el-form-item label="用户限次:">
            <div>以下至少选择一项为限制</div>
          </el-form-item>
          <div class="part-user" style="width: 50%; height: 50px; margin-left: 90px">
            <div class="left" style="width: 300px; line-height: 50px">每人每天可领取次数</div>
            <div class="right" style="flex: 1; height: 100; padding-left: 10px; line-height: 50px">
              <el-radio-group v-model="formData.isUserDayStock" style="margin-right: 20px">
                <el-radio :value="false" size="large">不限制</el-radio>
                <el-radio :value="true" size="large">限制</el-radio>
              </el-radio-group>
              <span v-if="+formData.isUserDayStock">次数：<el-input-number v-model="formData.userDayStock" :min="1" /></span>
            </div>
          </div>
          <div class="part-user" style="width: 50%; height: 50px; margin-left: 90px">
            <div class="left" style="width: 300px; line-height: 50px">每人可领取次数</div>
            <div class="right" style="flex: 1; height: 100; padding-left: 10px; line-height: 50px">
              <el-radio-group v-model="formData.isUserTotal" style="margin-right: 20px">
                <el-radio :value="false" size="large">不限制</el-radio>
                <el-radio :value="true" size="large">限制</el-radio>
              </el-radio-group>
              <span v-if="+formData.isUserTotal">次数：<el-input-number v-model="formData.userTotal" :min="1" /></span>
            </div>
          </div>

          <el-form-item label="活动限次:" style="margin-top: 20px">
            <div class="part-user" style="width: 53%; height: 50px">
              <div class="left" style="width: 300px; line-height: 50px">活动每天可发放次数</div>
              <div class="right" style="flex: 1; height: 100; padding-left: 10px; line-height: 50px">
                <el-radio-group v-model="formData.isDayStock" style="margin-right: 20px">
                  <el-radio :value="false" size="large">不限制</el-radio>
                  <el-radio :value="true" size="large">限制</el-radio>
                </el-radio-group>
                <span v-if="+formData.isDayStock">次数：<el-input-number v-model="formData.dayStock" :min="1" /></span>
              </div>
            </div>
            <div class="part-user" style="width: 53%; height: 50px">
              <div class="left" style="width: 300px; line-height: 50px">活动总共可发放次数</div>
              <div class="right" style="flex: 1; height: 100; padding-left: 10px; line-height: 50px">
                <el-radio-group v-model="formData.isTotal" style="margin-right: 20px">
                  <el-radio :value="false" size="large">不限制</el-radio>
                  <el-radio :value="true" size="large">限制</el-radio>
                </el-radio-group>
                <span v-if="+formData.isTotal">次数：<el-input-number v-model="formData.total" :min="1" /></span>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- <template #footer>
        
      </template> -->
    </el-card>

    <!-- 弹出层 start -->
    <el-dialog v-model="dialogVisible" title="选择优惠券" width="1300" :before-close="handleClose">
      <div class="table-box">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" row-key="id">
          <el-table-column type="selection" width="55" />

          <el-table-column label="券模版ID" prop="id" width="180" />
          <!-- <el-table-column label="券模板编码" width="100">
            <template #default>
              <span>-</span>
            </template>
          </el-table-column> -->
          <el-table-column label="券名称" prop="name" width="80" />
          <el-table-column label="券类型" width="120">
            <template #default="{ row }">
              <span v-if="row.typeId === 1">代金券</span>
              <span v-if="row.typeId === 2">商品兑换券</span>
              <span v-else>折扣券</span>
            </template>
          </el-table-column>
          <el-table-column label="券面值" width="100">
            <template #default="{ row }">
              <span>{{ row.parValue ? "¥ " + row.parValue : "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效时间">
            <template #default="{ row }">
              <span>{{ row.validityObject }} </span>
              <!-- <span>{{ row.validityObject[0] }}至{{ row.validityObject[1] }}</span> -->
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="180" />
          <el-table-column label="领取有效期" width="180">
            <template #default="{ row }">
              <span>领取后{{ row.validDay }}天有效</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :page-sizes="[10, 20, 50, 100]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onTableSubmit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 弹出层 end -->
  </div>
</template>

<!-- 小细节未做
  1.限制请求券的量
  2.回填表格的选中状态
  3.表单的校验
  4.删除功能
  5.
-->

<script setup lang="tsx" name="couponScan">
import { ref, reactive, watch, onMounted, onDeactivated } from "vue";
import {
  getFoodCouponList,
  createCmssalesPromotion,
  getCorecmssalespromotionDetail,
  editCorecmssalespromotion
} from "@/api/modules/coupon";
import { getMemberGradeList } from "@/api/modules/member";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";

// 接收路由传参信息
const route = useRoute();
const router = useRouter();
// 2-1.当用户编辑活动时触发
onMounted(async () => {
  if (route.query.id) {
    console.log(route.query.id);
    formData.value.id = route.query.id;

    // console.log(route.query.id);
    const res = await getCorecmssalespromotionDetail({ id: route.query.id });
    formData.value = res.data;
    console.log(res);
    // 2-1-1.回填会员问题
    if (res.data.userGradeList.length > 0) {
      // 如果数据一样多，那么就是全部会员
      if (memberList.value.length === res.data.userGradeList.length) {
        isApplyMember.value = 0;
      } else {
        isApplyMember.value = 1;
      }
      memberList.value.forEach(v => {
        if (res.data.userGradeList.some(e => v.id === e.id)) {
          v.checked = true;
        } else {
          v.checked = false;
        }
      });
    }
    // 2-1-2.回填优惠券
    checkRuleList.value = res.data.rule;
  }
});

// 顶部菜单栏选中
const activeIndex = ref("menu1");
const handleSelect = index => {
  // 菜单栏滚动到对应位置
  const anchor = document.getElementById(index);
  if (anchor) {
    anchor.scrollIntoView({ behavior: "smooth" });
  }
};

// 表单收集数据
let formData = ref({
  name: "",
  code: null,
  validityRange: [],
  noDate: false,
  desc: "",
  // 是否限制活动每天可发放次数
  isDayStock: false,
  // 每日限制值
  dayStock: 0,
  // 是否限制活动总共可发放次数
  isTotal: false,
  // 活动总共可发放次数
  total: 0,
  // 是否限制每人每天可领取次数
  isUserDayStock: false,
  // 每人每天可领取次数
  userDayStock: 0,
  // 是否限制每人可领取总次数
  isUserTotal: false,
  // 每人可领取总次数
  userTotal: 0,
  // 活动类型
  type: 1,
  // 适用会员等级
  userGradeList: [],
  // 选中的优惠券
  rule: []
});

// 表单校验规则
const scanRules = reactive({
  name: [{ required: true, message: "请填写活动名称" }],
  validityRange: [{ required: true, message: "请选择活动日期" }]
});

// 选择优惠券弹出层显示与隐藏
const dialogVisible = ref(false);

// 获取优惠券表格数据
const pageSize = ref(10);
const pageNum = ref(1);
const total = ref(0);
const tableData = ref<any[]>();
const onTableData = async () => {
  const { data } = await getFoodCouponList({ pageSize: pageSize.value, pageNum: pageNum.value });
  tableData.value = data.list;
  total.value = data.total;
  // console.log(data);
};
watch(
  () => dialogVisible.value,
  newValue => {
    if (newValue) {
      onTableData();
    }
  }
);

// 优惠券表格选择行时触发
let ruleList = ref<any[]>([]);
const handleSelectionChange = e => {
  ruleList.value = e;
  // console.log(ruleList.value);
  ruleList.value.forEach(e => (e.count = 1));
};
// 表格确认选中优惠券
const checkRuleList = ref<any[]>([]);
const onTableSubmit = () => {
  checkRuleList.value = ruleList.value;
  formData.value.rule = checkRuleList.value.map(e => ({ id: e.id, count: e.count }));
  // console.log(formData.value.rule);
  dialogVisible.value = false;
};

// 删除优惠券
const onDelRule = id => {
  ruleList.value = ruleList.value.filter(v => v.id !== id);
  checkRuleList.value = ruleList.value;
  formData.value.rule = checkRuleList.value.map(e => ({ id: e.id, count: e.count }));
  // console.log(formData.value.rule);
};
// 数字发生改变时触发,把收集的数据放入字段中
const handleChange = () => {
  formData.value.rule = checkRuleList.value.map(e => ({ id: e.id, count: e.count }));
  // console.log(formData.value.rule);
};

// 2-2.会员等级分类列表
const isApplyMember = ref(0);
const memberList = ref<any[]>([]);
const memberCheck = ref([]);
// const checkboxMember = ref();
const onMemberGradeList = async () => {
  const { data } = await getMemberGradeList({ pageNum: 1, pageSize: 9999 });
  // console.log(data);
  memberList.value = data.list;
};
// 监听需要会员时触发
watch(
  () => isApplyMember.value,
  newValue => {
    onMemberGradeList();
    if (!newValue) {
      // 当用户选择全部会员时
      formData.value.userGradeList = memberList.value.map(v => ({ id: v.id }));
      // 😟😟当选择全部取消勾选问题勾选问题，
      memberList.value.forEach(v => {
        v.checked = false;
      });
      console.log(memberList.value);
    }
  },
  { immediate: true }
);
// 选中会员时触发
const onChangeMember = e => {
  formData.value.userGradeList = e.map(v => ({ id: v }));
  // console.log(formData.value.userGradeList);
};

// 监听数据领取次数是否不限制状态，是将数据修改为0
watch(
  () => formData.value.isDayStock,
  newValue => {
    if (!newValue) formData.value.dayStock = 0;
  }
);
watch(
  () => formData.value.isTotal,
  newValue => {
    if (!newValue) formData.value.total = 0;
  }
);
watch(
  () => formData.value.isUserDayStock,
  newValue => {
    if (!newValue) formData.value.userDayStock = 0;
  }
);
watch(
  () => formData.value.isUserTotal,
  newValue => {
    if (!newValue) formData.value.userTotal = 0;
  }
);

// 条数发生改变时触发
const handleSizeChange = v => {
  pageNum.value = 1;
  pageSize.value = v;
  onTableData();
};
// 页码发生改变是触发
const handleCurrentChange = v => {
  pageNum.value = v;
  onTableData();
};

// 提交表单数据
const mssalesPromotionRef = ref();
const onSubmitMssalesPromotion = async () => {
  await mssalesPromotionRef.value.validate();
  if (!route.query.id) {
    // 添加
    await createCmssalesPromotion(formData.value);
    router.push({
      path: "/marketing/coupon-scan"
    });
    ElMessage.success("添加成功");
  } else {
    // 编辑
    const res = await editCorecmssalespromotion(formData.value);
    console.log(res);

    router.push({
      path: "/marketing/coupon-scan"
    });
    ElMessage.success("编辑成功");
  }
};

onDeactivated(() => {
  formData.value = {
    name: "",
    code: null,
    validityRange: [],
    noDate: false,
    desc: "",
    // 是否限制活动每天可发放次数
    isDayStock: false,
    // 每日限制值
    dayStock: 0,
    // 是否限制活动总共可发放次数
    isTotal: false,
    // 活动总共可发放次数
    total: 0,
    // 是否限制每人每天可领取次数
    isUserDayStock: false,
    // 每人每天可领取次数
    userDayStock: 0,
    // 是否限制每人可领取总次数
    isUserTotal: false,
    // 每人可领取总次数
    userTotal: 0,
    // 活动类型
    type: 1,
    // 适用会员等级
    userGradeList: [],
    // 选中的优惠券
    rule: []
  };
  checkRuleList.value = [];
  isApplyMember.value = 0;
});
</script>

<style lang="scss" scoped>
::v-deep .el-menu--horizontal.el-menu {
  height: 40px;
  border-bottom: none !important;
}
.active {
  padding-left: 20px;
  border-left: 5px solid #fdbf0e;
}
.part-user {
  display: flex;
  width: 80%;
  height: 150px;
  border: 1px solid #cccccc;
  .left {
    line-height: 150px;
    text-align: center;
    border-right: 1px solid #cccccc;
  }
  .right {
    line-height: 150px;
  }
}
</style>
